package com.zby.filter.util.core.util;

import com.alibaba.fastjson.JSONObject;
import com.zby.filter.util.PropertyUtil;
import com.zby.filter.vo.enums.TitleEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created By zby on 21:39 2019/2/13
 */

public class JsonUtil {



    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    /**
     * Created By zby on 9:40 2019/2/13
     * 模拟框架中的数据
     *
     * @param object 参数对象
     * @param props  String类型的变长数组，比如{"id:projectId", "mobile",...}
     *               前半部分是javabean的属性名，后半部分是返回到给客户端的参数名
     */
    public static JSONObject propsFilter(Object object, String... props) {
        //【1】判断对象和变长数组的是否为空，以及变长数组的长度是否为0
        boolean isNull = object == null || (null == props && props.length == 0);
        if (isNull) {
            logger.warn("参数为空object=" + object + "props=" + props);
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        for (String prop : props) {
            //【2】再判断对象不为空，或者长度不为0
            if (prop == null && prop.length() == 0) {
                logger.warn("参数为空prop= " + prop);
                throw new RuntimeException("参数为空prop=" + prop);
            }
            Object o = null;
            String[] namePair = StringUtils.split(prop, ":");
            try {
                o = PropertyUtil.getProperty(object, namePair[0]);
            } catch (Exception e) {
                logger.warn("类" + object.getClass() + "，属性" + namePair[0] + "不存在");
            }
            String key = namePair.length <= 1 ? namePair[0] : namePair[1];
            if (o instanceof Date)
                jsonObject.put(key, DateUtil.simpleFormate((Date) o));
            else if (o instanceof BigDecimal)
                jsonObject.put(key, CommonUtil.toFiexd((BigDecimal) o, 2));
            else if (o instanceof TitleEnum)
                jsonObject.put(key, CommonUtil.builderEnum((TitleEnum) o));
            else
                jsonObject.put(key, o);
        }
        return jsonObject;
    }
}
